package com.asman.vr.utils

import kotlin.math.max

/**
 * 字符串拼接，过滤null
 * Created by ybk on 2017/6/29.
 */
object StringAppendUtils {

    fun builder(): Builder {
        return Builder()
    }

    class Builder {
        private var append = ""

        fun append(str: String?): Builder {
            if (!str.isNullOrEmpty()) {
                append += str
            }
            return this
        }

        fun append(str: String?, condition: Boolean): Builder {
            if (!str.isNullOrEmpty() && condition) {
                append += str
            }
            return this
        }

        fun build(): String {
            return append
        }
    }


    /**
     * 拼接字符串
     * @param values 数组
     * @return String
     */
    fun stringAppend(values: Array<Any?>?): String {
        var str = ""
        values?.forEach {
            if (it != null && it.toString().isNotEmpty()) {
                str += it.toString()
            }
        }
        return str
    }


    /**
     * 拼接字符串，带分隔符
     * @param values  字符串数组
     * @param splitGroup 分隔字符
     */
    fun stringAppendSplit(values: Array<Any?>?, splitGroup: String?): String {
        return if (splitGroup.isNullOrEmpty()) {
            stringAppend(values)
        } else {
            var str = ""
            values?.forEach {
                if (it != null && it.toString().isNotEmpty()) {
                    str += it.toString() + splitGroup
                }
            }
            str.substring(0, max(0, str.length - splitGroup.length))
        }
    }


    /**
     * 拼接字符串 Key-Value
     * @param  keys arrayOf("户型", "面积", "价格")
     * @param  values arrayOf("2室2厅", "123㎡", "￥12321.1")
     * @param  splitKeyValue key和value之间的分隔符
     * @param  splitGroup 每组之间的分隔符
     * @returns 返回 '户型:2室2厅|面积:123㎡|价格:￥12321.1'
     */
    fun stringAppendKeyValue(
        keys: Array<Any?>?, values: Array<Any?>?, splitKeyValue: String?, splitGroup: String?
    ): String {
        var str = ""
        val splitKeyValue1 = splitKeyValue ?: ""
        val splitGroup1 = splitGroup ?: ""
        keys?.forEachIndexed { index, key ->
            if (values?.size != null && values.size > index) {
                val value = values[index]
                if (key != null && key.toString().isNotEmpty() && value != null && value.toString().isNotEmpty()) {
                    str += key.toString() + splitKeyValue1 + value + splitGroup1
                }
            }
        }

        return str.substring(0, max(0, str.length - splitGroup1.length))
    }
}